package pers.xx.sbm.service.serviceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import pers.xx.sbm.dao.RoleMapper;
import pers.xx.sbm.dao.UserRoleMapper;
import pers.xx.sbm.entity.User;
import pers.xx.sbm.entity.UserRole;
import pers.xx.sbm.enums.ResultEnum;
import pers.xx.sbm.service.UserRoleService;
import pers.xx.sbm.utils.UserUtils;
import pers.xx.sbm.vo.ResResult;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ：xiexing
 * @description：用户角色接口操作实现类
 * @date ：2020/9/20 18:22
 */
@Repository
public class UserRoleServiceImpl extends BaseServiceImpl<UserRole> implements UserRoleService {

    UserRoleMapper userRoleMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    UserUtils userUtils;

    public UserRoleServiceImpl(@Autowired UserRoleMapper userRoleMapper) {
        this.userRoleMapper = userRoleMapper;
        super.dao = userRoleMapper;
    }

    /**
     * @param userId 用户id
     * @description 根据用户id查询用户角色
     * @author XieXing
     * @date 2020/9/20 18:25
     */
    @Override
    public List<UserRole> findRolesByUserId(Integer userId) {
        return userRoleMapper.findRolesByUserId(userId);
    }

    @Override
    public ResResult<String> deleteByUserId(Integer userId) {
        userRoleMapper.deleteByUserId(userId);
        return new ResResult<>(ResultEnum.SUCCESS, "根据用户id删除用户角色成功!");
    }

    /**
     * @description 保存用户角色
     * @author XieXing
     * @date 2020/10/13 16:05
     */
    @Transactional //开启事务
    @Override
    public ResResult saveBatchUserRole(Integer userId, String roles) {
        User user = userUtils.getCurrentUser();
        userRoleMapper.deleteByUserId(userId);//先根据用户id删除用户角色
        String[] roleArr = roles.split(",");//获取角色数组
        List<UserRole> userRoles = new ArrayList<>();//用户角色数组
        for (int i = 0; i < roleArr.length; i++) {
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            if (StringUtils.isEmpty(roleArr[i])) {
                continue;
            }
            userRole.setRoleId(Integer.valueOf(roleArr[i]));
            userRole.setUserRoleAddTime(new Date());
            userRole.setUserRoleAddby(user.getUserName());
            userRole.setUserRoleAddbyId(user.getId());
            userRoles.add(userRole);
        }
        if (userRoles.size() > 0)
            userRoleMapper.insertBatch(userRoles);//批量插入用户角色
        return new ResResult(ResultEnum.SUCCESS, "用户角色保存成功");
    }

    /**
     * @description 获取用户角色 TODO 待优化
     * @author XieXing
     * @date 2020/10/14 10:21
     */
    @Override
    public List<Integer> getRoleIdsByUserId(Integer userId) {

        return userRoleMapper.getRoleIdsByUserId(userId);
    }
}
